// 云函数入口文件
const cloud = require('wx-server-sdk')
var request = require('request')


cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()
const tableName = 'userInfo'

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        // 从云开发数据库中查询等待发送的消息用户列表
        const weather = await db
            .collection(tableName)
            .get()
        console.log("location:", weather.data);

        for (const msgData of weather.data) {
            
            return new Promise((resolve, reject) => {
                var location = msgData.location
                console.log("location:", location)
                //调用天气API查询天气
                request({
                    url: 'https://jisutqybmf.market.alicloudapi.com/weather/query'+ "?location="+ location,
                    headers: {
                        "Authorization": "APPCODE b3ac862eeb284816b420cf88c990fbbc"
                    },
                    data: {
                        'location': location
                    },
                    method: "GET",
                    json: true,  //返回的body结果为json格式要不然解析不了数据
                },function (error,response,body) {
                        console.info("HTTP - GET")
                        console.info(body)
                        if (response.statusCode === 200 && !error && body.status == 0) {
                            var result = body.result;
                            console.info(result)
                            var weatherMessage = "当前天气" + result.weather + "气温" + result.temp + "℃" + "详情点击查看"
                            console.info("天气为：", weatherMessage)
                            //将天气信息添加数据库
                            db.collection(tableName)
                                .where({
                                    openid: msgData.openid
                                })
                                .update({
                                    data: {
                                        weatherMessage: weatherMessage,
                                    }
                                })
                                .then((res) => {
                                    console.log("定时添加天气信息到数据库成功", res);
                                    resolve(body)
                                })
                                .catch((res) => {
                                    console.log("定时添加天气信息到数据库失败", res);
                                    reject()
                                });
                        }
                    }
                )
            })

        }
    }
    catch (e) {
        console.log(e)
        return e
    }
}